import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/pages/subpackage/share_page.dart';
import 'package:flutter_give/pages/subpackage/videosetting_page.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';
import '../../common_ui/dialog/dialog_factory.dart';
import '../../repository/api.dart';
import '../../tgpage/event/notification.dart';
import '../../tgpage/media/cloud_replay.dart';
import '../../theme.dart';
import '../Home/home_page.dart';
import '../Home/home_vm.dart';
import 'Eqrestart_page.dart';
import 'firmware_page.dart';
import 'frames_page.dart';
import 'memorycard_page.dart';
import 'moresetting_page.dart';
import 'nightvision_page.dart';

/// 设备设置页面
class EqsettingPage extends StatefulWidget {
  final String deviceId;
  final String deviceName;
  final String ID;

  const EqsettingPage(
      {super.key, required this.deviceId, required this.deviceName,required this.ID});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _EqsettingPageState();
  }
}

class _EqsettingPageState extends State<EqsettingPage> {
  // 获取类
  HomeViewModel viewModel = HomeViewModel();

  late String _deviceId;
  late String _deviceName;
  late String _ID;

  // 指令示例
  late Pipe _pipe;

  // 录音保护
  int _isSwitched = 0;

  // 移动追踪 - 值
  int _istraceSwtiched = 0;
  // 移动追踪 - 是否支持（0-不支持）
  int _istracesupport = 0;

  @override
  void initState() {
    // 执行
    super.initState();

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff), // 设置状态栏颜色
      statusBarIconBrightness: Brightness.dark, // 设置状态栏图标亮度为暗色
    ));

    _deviceId = widget.deviceId;
    _deviceName = widget.deviceName;
    _ID = widget.ID;

    LogUtils.w("设备ID${_deviceId}");
    LogUtils.w("设备ID${_deviceName}");

    // 创建实例
    _pipe = Pipe.create(_deviceId);

    // 2. 监听“连接状态”以作出响应
    _pipe.listen((state) {
      LogUtils.w(state);
      if (state == PipeState.established) {
        // 连接成功建立，可以启动视频播放、发送指令或者其他操作了
        _onQuality();
        // 移动侦测
        _alloW();
      }
    });
    // 连接设备
    _pipe.establish();

    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   _onQuality();
    // });
  }

  @override
  void dispose() {
    super.dispose();
    // 销毁实例
    _pipe.abolish();
    _pipe.destroy();
  }

  // 录音保护
  void _onQuality() async {
    // LogUtils.w("========执行1=======");
    if (!_pipe.isEstablished) return;
    // LogUtils.w("========执行2=======");
    final resp = await InstructStandard.microphoneSwitch(_pipe);
    if (!mounted) return;
    if (resp.success) {
      LogUtils.w(resp.data);
      setState(() {
        _isSwitched = resp.data ?? 0;
      });
    } else {
      showToast("获取画面设置失败");
    }
  }

  // 追踪
  void _alloW() async {
    LogUtils.w("========执行1=======");
    if (!_pipe.isEstablished) return;
    LogUtils.w("========执行移动侦测=======");
    final resp = await InstructStandard.motionTrackingState(_pipe);
    if (!mounted) return;
    if (resp.success) {
      // 当前模式 1-关 0-开
      LogUtils.w(resp.data?.mode);
      // 是否支持 0 - 不支持
      LogUtils.w(resp.data?.support);
      // 更新视图数据
      setState(() {
        showToast("获取配置成功");
        _istraceSwtiched = resp.data!.mode;
        _istracesupport = resp.data!.support;
      });
    } else {
      showToast("获取画面设置失败");
    }
  }

  // widget.title-要等页面初始化之后才能使用
  // Widget-有状态组件-需要使用setState 更新
  // StateLessWidget-无状态组件
  Future<bool> _onWillPop() async {
    // 监听返回按钮操作
    LogUtils.w("用户点击了返回按钮");
    HomePageState.globalKeytwo.currentState?.reloadData();
    return true; // 返回true表示允许返回，返回false表示阻止返回
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          // appBar: AppBar(title: Text(widget.title?? "")),
          appBar: _buildTitleBar(context),
          body: _buildRootBody(context),
        ),
        onWillPop: _onWillPop);
  }

  // 主体
  Widget _buildRootBody(BuildContext context) {
    return Container(
      color: Color(0xFFF2F3F5), // 设置背景颜色为灰色
      child: SafeArea(
        child: SingleChildScrollView(
          // 添加滚动视图
          padding: const EdgeInsets.all(16.0), // 设置内边距
          child: Column(
            // crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildbasicsRow(),
              SizedBox(height: 10),
              Container(
                alignment: Alignment.centerLeft, // 左对齐
                child: Text(
                  "告警设置",
                  style: TextStyle(color: Color(0xFFb2b2b2)),
                  textAlign: TextAlign.left, // 文字左对齐
                ),
              ),
              SizedBox(height: 10),
              _buildreportRow(),
              SizedBox(height: 10),
              Container(
                alignment: Alignment.centerLeft, // 左对齐
                child: Text(
                  "其他设置",
                  style: TextStyle(color: Color(0xFFb2b2b2)),
                  textAlign: TextAlign.left, // 文字左对齐
                ),
              ),
              SizedBox(height: 10),
              _buildrestRow(),
              SizedBox(height: 40),
              _buildLogoutButton(),
              SizedBox(height: 25),
            ],
          ),
        ),
      ),
    );
  }

  // 删除设备
  Widget _buildLogoutButton() {
    return SizedBox(
      width: 270, // 设置按钮宽度为400
      height: 45, // 设置按钮高度为40
      child: ElevatedButton(
        onPressed: () {
          DialogFactory.instance.showNeedeqListDialog(
              context: context,
              dismissClick: () {},
              confirmClick: () async {
                // 判断设备是否在线
                // final resp = await BindingService.unbind(_deviceId ?? "");
                // if (!context.mounted) return;
                // if (resp.success) {
                //   showToast("删除成功");
                //   Navigator.of(context).pop();
                //   HomePageState.globalKeytwo.currentState?.reloadData();
                //   viewModel.getTANGEList();
                // } else {
                //   showToast("删除失败");
                // }

                bool swticheq = await Api.instance
                    .equnbundle(deviceid: "${_ID}");
                if (!context.mounted) return;
                if (swticheq) {
                  showToast("删除成功");
                  HomePageState.globalKeytwo.currentState?.reloadData();
                  Navigator.of(context).pop();
                } else {
                  showToast("删除失败");
                }
              });
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: Color(0xFFececec),
          foregroundColor: Color(0xFFececec),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 80),
          // 调整水平内边距
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '删除设备',
          style: TextStyle(fontSize: 16, color: Color(0xFFfc3d49)),
          textAlign: TextAlign.center, // 确保文字居中
        ),
      ),
    );
  }

  // 基础设置
  Widget _buildbasicsRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 7, // 上边距
        bottom: 7, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(
              //     builder: (context) => FirmwarePage(
              //       deviceId: _deviceId,
              //     ),
              //   ),
              // );
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => FirmwareminiPage(
                            deviceId: _deviceId ?? "",
                            deviceName: _deviceName,
                            ID:_ID
                          )));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '设备详情',
                    style: TextStyle(fontSize: 16),
                  ),
                  Row(
                    children: [
                      Text(
                        _deviceName,
                        style: TextStyle(fontSize: 16),
                      ),
                      SizedBox(width: 5),
                      Icon(Icons.arrow_forward_ios,
                          size: 16, color: Color(0xFF5a5a5a)),
                    ],
                  ),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => CloudReplayPage(
                            deviceId: _deviceId,
                            deviceName: _deviceName,
                          )));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '云录像',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          ShareminiPage(deviceId: _ID ?? "")));
              ShareminiPageState.globalKeyshare.currentState?.reloadData();

            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '分享',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              // 这里可以添加点击事件的处理逻辑
            },
            child: Container(
              padding: EdgeInsets.only(
                top: 0, // 上边距
                bottom: 0, // 下边距
                left: 10, // 左边距
                right: 5, // 右边距
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '录音保护',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        '关闭后，不会采集声音，以保护你的隐私',
                        style: TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                    ],
                  ),
                  Transform.scale(
                    scale: 0.8, // 缩小0.8倍
                    child: Switch(
                      value: _isSwitched == 1, // 1 表示开，0 表示关
                      activeTrackColor: SampleThemeConfigure.colorPrimary,
                      onChanged: (value) async {
                        print(value); // 打印开关状态
                        if (value) {
                          setState(() {
                            _isSwitched = 1; // 设置为 1 表示开
                          });
                        } else {
                          setState(() {
                            _isSwitched = 0; // 设置为 0 表示关
                          });
                        }
                        LogUtils.w(_isSwitched);

                        final resp = await InstructStandard.setMicrophoneSwitch(_pipe, _isSwitched);
                        if (!mounted) return;
                        if (resp.success) {
                          showToast("录音保护设置成功");
                        } else {
                          showToast("录音保护设置失败");
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          FramesPage(deviceId: _deviceId ?? "")));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '画面设置',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          NightvisionPage(deviceId: _deviceId ?? "")));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '夜视模式',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          VideosettingPage(deviceId: _deviceId ?? "")));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '录像设置',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          MemorycardPage(deviceId: _deviceId ?? "")));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '存储卡',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 告警设置
  Widget _buildreportRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 7, // 上边距
        bottom: 7, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          NotificationPage(deviceId: _deviceId ?? "")));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '消息通知设置',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '智能追踪',
                    style: TextStyle(fontSize: 16),
                  ),
                  Transform.scale(
                    scale: 0.8, // 缩小0.8倍
                    child: Switch(
                      value: _istraceSwtiched == 1, // 0 表示开，1 表示关
                      activeTrackColor: SampleThemeConfigure.colorPrimary,
                      onChanged: (value) async {
                        print(value); // 打印开关状态
                        if (_istracesupport == 0) {
                          showToast("设备不支持");
                          return;
                        }
                        if (value) {
                          setState(() {
                            _istraceSwtiched = 1; // 设置为 1 表示开
                          });
                        } else {
                          setState(() {
                            _istraceSwtiched = 0; // 设置为 0 表示关
                          });
                        }
                        LogUtils.w(_istraceSwtiched);

                        final resp = await InstructStandard.setMotionTrackingState(_pipe, _istraceSwtiched);
                        // final resp = await InstructStandard.setMotionTrackingState(_pipe, 0);
                        if (!mounted) return;
                        if (resp.success) {
                          showToast("设置成功");
                        } else {
                          showToast("设置失败");
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
          // InkWell(
          //   onTap: () {},
          //   child: Container(
          //     padding: EdgeInsets.all(13.0), // 设置内边距
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //       children: [
          //         Text(
          //           '移动侦测',
          //           style: TextStyle(fontSize: 16),
          //         ),
          //         Icon(Icons.arrow_forward_ios,
          //             size: 16, color: Color(0xFF5a5a5a)),
          //       ],
          //     ),
          //   ),
          // ),
          // InkWell(
          //   onTap: () {},
          //   child: Container(
          //     padding: EdgeInsets.all(13.0), // 设置内边距
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //       children: [
          //         Text(
          //           '警戒语音',
          //           style: TextStyle(fontSize: 16),
          //         ),
          //         Icon(Icons.arrow_forward_ios,
          //             size: 16, color: Color(0xFF5a5a5a)),
          //       ],
          //     ),
          //   ),
          // ),
        ],
      ),
    );
  }

  // 其他设置
  Widget _buildrestRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 7, // 上边距
        bottom: 7, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          EqrestartPage(deviceId: _deviceId)));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '重启设备',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          MoresettingPage(deviceId: _deviceId, Eqid: _ID,)));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '更多设置',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 导航
  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios), // 使用没有横线的返回箭头图标
        onPressed: () {
          _onWillPop();
          // 返回操作
          Navigator.of(context).pop();
        },
      ),
      backgroundColor: Colors.white,
      automaticallyImplyLeading: false,
      // 禁用自动生成的返回按钮
      title: Text(
        "摄像机设置",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }
}
